var Personnel = function() {

    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var detail_url = $('.detail_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();

    var checkUsername_url = $('.checkUsername_url').val();

    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {
                        "data": "p_imgUrl",
                        "render": function(data, type, row, meta) {
                            return '<a href="'+data+'" target="_blank"><img src="'+data+'" style="width: 60px;height: 40px;"/></a>';
                        }
                    },
                    {"data": "p_name"},
                    {
                        "data": "sex",
                        "render": function(data, type, row, meta) {
                            return data == 1 ? '男' : '女';
                        }
                    },
                    {"data": "department"},
                    {"data": "duties"},
                    {"data": "p_phone"},
                    {
                        "data": "is_partymember",
                        "render": function(data, type, row, meta) {
                            return data == 1 ? '党员' : '-';
                        }
                    },
                    {"data": "createDate"},
                    {
                        "width": "20%",
                        "render": function(data, type, row, meta) {
                            var html = '';
                            html += '<a href="'+detail_url+'?id='+row.id+'" type="button" class="btn btn-info">详情</a>';
                            html += '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                            html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [7, "desc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0,1,2,3,4,5,6,8]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                }
            });
        }


        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var tableSearch = function(table, params) {
        table.DataTable().search(JSON.stringify(params)).draw();
    };

    // 初始化 是否为党员
    var init_isParty = function() {
        var isParty = $("input[name='is_partymember']:checked").val();
        if(isParty == 1) {
            $('.party').removeClass('hide');
        } else {
            $('.party').addClass('hide');
        }
    };

    // 表单提交
    var submitForm = function(btnObj) {
        var form = document.getElementById("ajax-form");
        var _this = btnObj;

        if(form.name.value.trim()=='') {
            layer.msg('请输入姓名');
            form.name.focus();
            return;
        }
        if(form.departmentId.value.trim()==0) {
            layer.msg('请选择部门');
            form.departmentId.focus();
            return;
        }
        if(form.p_phone.value.trim()=='') {
            layer.msg('请输入手机');
            form.p_phone.focus();
            return;
        }
        if(form.is_partymember.value.trim()==1){
            if(form.partyTime.value.trim()==''){
                layer.msg('请选择入党时间');
                form.partyTime.focus();
                return;
            }
        }
        if(form.posttype.value.trim()=='add'){
            if(form.username.value.trim()=='') {
                layer.msg('请输入登录账号');
                form.username.focus();
                return;
            }
        }

        var _data = $(form).serializeObject();
        _this.prop("disabled", true);
        $.ajax({
            url : save_url,
            type : 'post',
            dataType : 'json',
            contentType : "application/json; charset=utf-8",
            data : JSON.stringify(_data),
        }).done(function(data) {
            if (data.code == 1) {
                layer.msg('保存成功');
                window.location.href = data.url; //加载页面数据
            } else if (data.code === 0 ) {  // 错误
                _this.prop("disabled", false);
                layer.msg(data.msg);
            }
        });
    };


    return {
        init: function() {
            initTable();
            init_isParty();

            this.onEvent();
        },

        onEvent : function(){

            $('#doSearch').on('click', function(event){
                var table = $('#data-table');
                if(!table.is(':visible')){
                    table = $('#checkdata-table');
                }

                var param = $('#searchForm').serializeObject();
                tableSearch(table, param);
            });

            // 切换 是否为党员
            $('.isparty label input').on('click', function(){
                init_isParty();
            });

            $("#username").blur(function(){
                var username = $(this).val();
                $.ajax({
                    url: checkUsername_url,
                    type: 'POST',
                    data: {'username': username},
                    dataType : 'json',
                    success: function (data) {
                        if(data.status == 1){
                            $('#username').css('background-color', 'lightpink');
                            layer.msg('该登录帐号已经存在！');
                            $('#username').focus();
                            $('#form-submit').prop("disabled", true);
                        }else {
                            $('#username').css('background-color', 'white');
                            $('#form-submit').removeAttr("disabled");
                        }
                    }
                });
            });

            $('#form-submit').on('click', function () {
                var form = this.form;
                var _this = $(this);

                if(form.name.value.trim()=='') {
                    layer.msg('请输入姓名');
                    form.name.focus();
                    return;
                }
                if(form.departmentId.value.trim()==0) {
                    layer.msg('请选择部门');
                    form.departmentId.focus();
                    return;
                }

                if(form.p_phone.value.trim()=='') {
                    layer.msg('请输入手机');
                    form.p_phone.focus();
                    return;
                }
                if(form.is_partymember.value.trim()==1){
                    if(form.partyTime.value.trim()==''){
                        layer.msg('请选择入党时间');
                        form.partyTime.focus();
                        return;
                    }
                }
                if(form.posttype.value.trim()=='add'){
                    if(form.username.value.trim()=='') {
                        layer.msg('请输入登录账号');
                        form.username.focus();
                        return;
                    }

                    var username = form.username.value;
                    var url = checkUsername_url;
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: {'username': username},
                        dataType : 'json',
                        success: function (data) {
                            if(data.status == 1){
                                layer.msg('该登录帐号已经存在！');
                                $('#username').focus();
                                return false;
                            }else{
                                submitForm(_this);
                            }
                        }
                    });
                    return false;
                }

                submitForm(_this);
            });

            // 模板下载
            $('#download_template').on('click', function(){
                var url = $(this).data('url');
                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });

            // 批量导入
            $('#import_csv').on('click', function(){
                var csv_file = $('input[name=csv_file]').val();
                var point = csv_file.lastIndexOf(".");

                var type = csv_file.substr(point);
                type = type.toLowerCase();
                if(type != ".csv" && type != ".xls" && type != ".xlsx"){
                    layer.msg('请选择csv, xls, xlsx文件');
                    return false;
                }

                var url = $('#import_form').attr('action');
                var data = new FormData();
                var csv_file = document.getElementById('csv_file').files[0];
                data.append('csv_file', csv_file);

                layer.load(2, {shade: [0.8,'#000000']}); // 打开loading
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    //dataType : 'json',
                    processData: false,
                    contentType: false,
                    success: function (data) {
                        layer.closeAll('loading'); // 关闭loading
                        layer.msg(data.msg);
                        if(data.status == 1){
                            window.location.reload();
                        }
                    }
                });
                return false;
            });

            // 批量导出
            $('#export_csv').on('click', function(){
                var url = $(this).data('url');

                var name = $('#searchForm').find('input[name=p_name]').val();
                //var departmentId = $("#searchForm").find('select[name=departmentId]').val();
                var departmentId = $('.departmentId').val();

                var $form = '<form id="export_form" action="'+url+'" method="post" style="display: none;">';
                $form += '<input name="p_name" value="'+name+'" >';
                $form += '<input name="departmentId" value="'+departmentId+'" >';
                $form += '</form>';
                if($(document).find('#export_form').length){
                    $(document).find('#export_form').remove();
                }
                $(document.body).append($form);
                // 提交表单，实现下载
                $(document).find('#export_form').submit();
            });
        }
    };

}();

$(function() {
    Personnel.init();
});
